package com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.screen.repay

import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.helasasa.maxfunds.lineofcredit.cashloan.ProjectApplication
import com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.http.IApiProcessCameroonCallback
import com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.http.createApiActionCameroon
import com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.http.doPostRequestCameroon
import com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.user.mainProcessFormatCameroon
import org.json.JSONArray
import org.json.JSONObject
import java.math.BigDecimal

class RepayCameroonViewModel : ViewModel() {

    private val _loadingResult = MutableLiveData<Boolean>()
    val loadingResult: LiveData<Boolean> = _loadingResult

    private val _pageDetailResult = MutableLiveData<RepayCameroonResult>()
    val pageDetailResult: LiveData<RepayCameroonResult> = _pageDetailResult

    private val _repayUrlResult = MutableLiveData<RepayCameroonUrlResult>()
    val repayUrlResult: LiveData<RepayCameroonUrlResult> = _repayUrlResult

    private val _mainProcessResult = MutableLiveData<RepayCameroonMainProcessResult>()
    val mainProcessResult: LiveData<RepayCameroonMainProcessResult> = _mainProcessResult

    private val _nextRouterResult =
        MutableLiveData<RepayCameroonNextRouterResult<AppCompatActivity>>()
    val nextRouterResult: LiveData<RepayCameroonNextRouterResult<AppCompatActivity>> =
        _nextRouterResult

    var orderId: String = ""
    var isFirstLoad: Boolean = true

    /** 获取页面详情接口 */
    fun pageDetail() {
        if (this.orderId.isBlank()) {
            _pageDetailResult.value = RepayCameroonResult(error = "Order id is null")
            return
        }

        _loadingResult.value = true
        val context = ProjectApplication.context
        val action = hashMapOf<String, Any>().createApiActionCameroon()
        action["path"] = "NJ4WYHSJ4dP1oMvJWhJ4Yg"
        action["orderId"] = this.orderId

        context.doPostRequestCameroon(action, object : IApiProcessCameroonCallback {
            override fun onApiReady() {
            }

            override fun onApiDone(jsonObject: JSONObject) {
                _loadingResult.value = false

                val obj = jsonObject.optJSONObject("obj") ?: JSONObject()

                // 金额格式化
                val totalRepay = obj.optString("repayAmount", "0")

                // 转成不带.0结尾的值
                val totalRepayBigString =
                    BigDecimal(totalRepay).stripTrailingZeros().toPlainString()

                // 更新
                obj.put("totalRepay", totalRepayBigString)

                val array = obj.optJSONArray("repayList") ?: JSONArray()
                val list = mutableListOf<JSONObject>()
                for (index in 0 until array.length()) {
                    val item = array[index] as JSONObject
                    list.add(item)
                }
                _pageDetailResult.value = RepayCameroonResult(success = obj, list = list)
            }

            override fun onApiError(code: String, errMsg: String) {
                _loadingResult.value = false

                _pageDetailResult.value = RepayCameroonResult(error = errMsg)
            }
        })

    }


    /** 还款链接接口 */
    fun repayUrl() {
        _loadingResult.value = true

        val context = ProjectApplication.context
        val action = hashMapOf<String, Any>().createApiActionCameroon()
        action["path"] = "v9bdlZ373VH82GFo9VqvA"

        context.doPostRequestCameroon(action, object : IApiProcessCameroonCallback {
            override fun onApiReady() {
            }

            override fun onApiDone(jsonObject: JSONObject) {
                _loadingResult.value = false

                val obj = jsonObject.optJSONObject("obj") ?: JSONObject()
                val url = obj.optString("url")
                val repayUrl = obj.optString("repayUrl")
                val validUrl = url.ifBlank { repayUrl }
                if (validUrl.isNotBlank()) {
                    _repayUrlResult.value = RepayCameroonUrlResult(success = validUrl)
                } else {
                    _repayUrlResult.value = RepayCameroonUrlResult(error = "Erreur de création du lien de remboursement")
                }
            }

            override fun onApiError(code: String, errMsg: String) {
                _loadingResult.value = false

                _repayUrlResult.value = RepayCameroonUrlResult(error = errMsg)
            }
        })
    }

    /** 查询主流程接口 */
    fun mainProcess() {
        _loadingResult.value = true

        val context = ProjectApplication.context
        val action = hashMapOf<String, Any>().createApiActionCameroon()
        action["path"] = "D50PrK3UELaosdHcVCL7A"

        context.doPostRequestCameroon(action, object : IApiProcessCameroonCallback {
            override fun onApiReady() {
            }

            override fun onApiDone(jsonObject: JSONObject) {
                _loadingResult.value = false

                val obj = jsonObject.optJSONObject("obj")
                _mainProcessResult.value = RepayCameroonMainProcessResult(success = obj)
            }

            override fun onApiError(code: String, errMsg: String) {
                _loadingResult.value = false

                _mainProcessResult.value = RepayCameroonMainProcessResult(error = errMsg)
            }
        })

    }

    /** 页面跳转 */
    fun nextRouter(jsonObject: JSONObject) {
        // 判断下一步
        val nextRouterResult = jsonObject.mainProcessFormatCameroon(fromRepayDetail = true)
        if (nextRouterResult.nextRouter != null) {
            _nextRouterResult.value =
                RepayCameroonNextRouterResult(nextPage = nextRouterResult.nextRouter)
        }
    }
}